package com.pro.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pro.domain.User;
import com.pro.service.UserService;
import com.pro.util.R;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Controller
@CrossOrigin
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Value("${jwt.secret}")
    private String secret;

    //去登录页面
    /*http://localhost:8883/yzmlogin/tologin*/
    @RequestMapping("/tologin")
    public String tologin(){
        return "redirect:http://localhost:8885/yzmfront/login.html";
    }

    @RequestMapping("/Login")
    @ResponseBody
    public R Login(String mobile, String yanzhengma){
        Map map = userService.LoginCheck(mobile, yanzhengma);
        String stringmsg = (String) map.get("msg");
        Integer code = (Integer) map.get("code");
        try {
            if(code!=300){
                //只要登录成功，用户信息-jwt->token串-->发到前端，保存
                User loginUser = (User) map.get("LoginUser");
                Map<String,Object> claims=new HashMap<>();
                claims.put("username",loginUser.getUsername());
                claims.put("password",loginUser.getPassword());
                //生成token
                String token = Jwts.builder()
                        .setClaims(claims)
                        .signWith(SignatureAlgorithm.HS256,secret)
                        .compact();
                //token->redis （token放到redis中）
                String redisTokenKey="Ren_token_"+token;
                ObjectMapper objectMapper=new ObjectMapper();
                String tokenValue = objectMapper.writeValueAsString(loginUser);
                //把什么放入了redis中？key：token，value：user
                stringRedisTemplate.opsForValue().set(redisTokenKey,tokenValue, Duration.ofHours(1));
                //每次访问后台时，都带上token
                //作为后端，token是否要保存？-->redis,k-v
                //前端->后端，把放在头信息中的token，组合一个key，在获取这个key对应的值
                //给这个redis中的key设置时长。
                //如果断断续续在使用程序，那在操作的时候，可以延续key的时长，
                map.put("loginUser",loginUser);
                map.put("token",token); //这个token先这样写
                System.out.println(stringmsg);
                return new R(200,"登陆成功",map);
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return new R(200,"失败");
        }
        System.out.println(stringmsg);
        return new R(300,"登录失败");
    }
}
